/*
 * PIT.c
 *
 *  Created on: Nov 11, 2013
 *      Author: Efrain
 */



#include "derivative.h"
#include "Mytypes.h"
#include "PIT.h"
#include "Camera.h"

uint16 Enable_Delay;
uint8 u8_ADC_Camera_1[128];
uint8 u8_ADC_Camera_2[128];
uint8 u8_Pixel_index;

/**************************************************************
 *  Name                 : vdfn_PIT_Init
 *  Description          : Configures PIT
 *  Parameters           : none
 *  Return               : none
 *  Critical/explanation : It helps to obtain cameras frames in a synchronised way with the ADC
 **************************************************************/
void vdfn_PIT_Init(void){
	SIM_SCGC6 |= SIM_SCGC6_PIT_MASK; //Clock Gating for PIT Enable 
	PIT_MCR = PIT_MCR_FRZ_MASK;// | (0 << 30); // Allows Freezing Counters when debugging | Enables/Disables PIT timers.
	PIT_LDVAL1 = 230; //50000 counts
	PIT_TCTRL1 |= PIT_TCTRL_TIE_MASK; // Timer Interrupt Enable 
	//PIT_TCTRL1 |= PIT_TCTRL_TEN_MASK; //Timer Enable
	//PIT_TCTRL1 |= PIT_DISABLE;
	PIT_TCTRL1 |= PIT_ENABLE;
	
}

void PIT_IRQHandler(void){
		PIT_TFLG1 = 1; //Clears flag writing 1 on Flag register.
		
		if(ENABLE_SI == 1 && ((GPIOE_PDOR && 0x02) == 0x00)){
			Enable_Delay = 0;
			ENABLE_SI = 0;
			GPIOD_PSOR = GPIO_PSOR_PTSO(128); 
			GPIOE_PTOR |= (1<<1); //Toggle GPIO to simulate a CLK source for the camera.
			for(;Enable_Delay <=3;Enable_Delay++)
			{							}
			GPIOD_PCOR = GPIO_PCOR_PTCO(128);
			u8_Pixel_index = 0;
		}
		else 
		GPIOE_PTOR |= (1<<1); //Toggle GPIO to simulate a CLK source for the camera.
		//(void)ADC0_SC1B;
		while((ADC0_SC1B & 128) == 0) // 1 = Conversion completed, 0 = conversion is not completed
		{								}
			
		if(u8_Pixel_index <= 128){
			if((GPIOE_PDOR & 0x02) == 0x02){
				u8_ADC_Camera_1[u8_Pixel_index] = ADC0_RB;
				ADC0_SC1B = ADC_SC1_ADCH(7);
			}
			else{
				u8_ADC_Camera_2[u8_Pixel_index] = ADC0_RB;
				ADC0_SC1B = ADC_SC1_ADCH(6);
				u8_Pixel_index++;
					
			}			
		}
				
		//ADC0_SC1B = ADC_SC1_ADCH(6); // Esta linea tiene que estar cambiando dentro de la tarea entre 6 y 7, un canal por camara,  11111 (31) = Disabled
		
		
}
